from django.conf import settings
from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer


def generate_encrypted_openid(openid):
    """
    生成加密的openid
    :param openid: 用户的openid
    """
    serializer = TimedJSONWebSignatureSerializer(
        settings.SECRET_KEY, expires_in=600)
    data = {'openid': openid}
    return serializer.dumps(data).decode()


def check_encrypted_openid(encrypted_openid):
    """
    校验openid有效性
    """
    serializer = TimedJSONWebSignatureSerializer(
        settings.SECRET_KEY, expires_in=600)
    try:
        data = serializer.loads(encrypted_openid)
    except BadData:
        return None
    else:
        return data.get('openid')
